package com.redrose.audioandvideo.camera;

import android.hardware.Camera;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.redrose.audioandvideo.R;
import com.redrose.audioandvideo.bean.Photo;
import com.redrose.audioandvideo.bean.Time;
import com.redrose.audioandvideo.databinding.ActivityCameraBinding;
import com.redrose.audioandvideo.runnabletask.SaveImageRunnable;
import com.redrose.audioandvideo.ui.activitys.BaseActivity;
import com.redrose.audioandvideo.utils.BitmapCallBack;
import com.redrose.audioandvideo.utils.FileUtil;
import com.redrose.audioandvideo.utils.GlideUtil;
import com.redrose.audioandvideo.utils.LogUtils;
import com.redrose.audioandvideo.utils.PathUtil;
import com.redrose.audioandvideo.utils.ThreadTask;
import com.redrose.audioandvideo.widget.PreViewGlsurfaceView;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author suxiaolei
 * @version 1.0
 * @date 20-5-6
 * @des 相机
 **/
@Route(path = "/activity/video")
public class VideoActivity extends BaseActivity<ActivityCameraBinding> implements BitmapCallBack {

    private List<Photo> mPhotoList;
    private Time mTime;

    @Override
    public void initData() {
        mBinding.setVideohandler(new VideoHandler());
        mBinding.glCamera.setBitmapCallback(this);
        mTime = new Time();
        mPhotoList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        String format = sdf.format(calendar.getTime());
        mTime.setClassId(Long.parseLong(format));
        mTime.setDay(calendar.get(Calendar.DAY_OF_MONTH));
        mTime.setYear(calendar.get(Calendar.YEAR));
        mTime.setMonth(calendar.get(Calendar.MONTH) + 1);
    }

    @Override
    public int setLayout() {
        initState();
        return R.layout.activity_camera;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (CameraUtil.getInstance().getIsPreview()) {

        }
        return super.onTouchEvent(event);
    }

    public class VideoHandler {
        public void onClickView(View v) {
            int id = v.getId();
            switch (id) {
                case R.id.tv_take_photo:
                    showSnackbar("拍照模式");
                    mBinding.glCamera.setModel(PreViewGlsurfaceView.TAKE_PHOTO_MODEL);
                    break;
                case R.id.tv_take_video:
                    showSnackbar("录像模式");
                    mBinding.glCamera.setModel(PreViewGlsurfaceView.TAKE_VIDEO_MODEL);
                    break;
                case R.id.im_preview:
                    if (mPhotoList.size() == 0) {
                        showSnackbar("当前没有拍摄");
                        return;
                    }
                    ARouter.getInstance()
                            .build("/activity/previewactivity")
                            .withParcelableArrayList("mPhotoList", (ArrayList<Photo>) mPhotoList)
                            .navigation();
                    break;
                case R.id.im_images:
                    ARouter.getInstance()
                            .build("/activity/imageActivity")
                            .navigation();
                    break;
                default:
                    break;
            }
        }

        public void takePhotoOrVideo() {
            int photoOrVideo = mBinding.glCamera.getModel();
            /** 拍照模式*/
            if (photoOrVideo == PreViewGlsurfaceView.TAKE_PHOTO_MODEL) {
                mBinding.glCamera.takePhoto();

                /** 录像模式*/
            } else {
                if (mBinding.glCamera.isStartVideo()) {
                    mBinding.glCamera.stopVideo();
                } else {
                    mBinding.glCamera.startVideo();
                }
            }
        }

        public void getPreSize(View v) {
            int id = v.getId();
            showSnackbar("当前没有拍摄");
            switch (id) {
                case R.id.btn_pre:
                    getCameraPreSize();
                    break;
                case R.id.btn_save:
                    getCameraSupportSaveSize();
                    break;
                case R.id.btn_zoom:
                    getZoomCamera();
                    break;
                default:
                    break;
            }

        }

    }


    @Override
    public void backByte(byte[] data) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        String format = sdf.format(calendar.getTime());
        //byte图片转文件存储
        GlideUtil.loadImage(mContext, data, mBinding.imPreview);
        saveImage(calendar, data, mPhotoList);
        List<Time> times = DataSupport.where("classId = ?", format).find(Time.class);
        mTime.setPhotoList(mPhotoList);
        if (times.size() == 0) {
            mTime.save();
        }
    }

    private void saveImage(Calendar calendar, byte[] date, List<Photo> list) {
        //先保存到数据库，然后写入磁盘，保证数据的绝对性
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
        String format = sdf.format(calendar.getTime());
        String path = PathUtil.getAppPicPath() + format + ".jpg";
        Photo photo = new Photo();
        photo.setDay(calendar.get(Calendar.DAY_OF_MONTH));
        photo.setMonth(calendar.get(Calendar.MONTH) + 1);
        photo.setClassId(Long.parseLong(format.substring(0, 8)));
        photo.setName(format);
        photo.setTime(format);
        photo.setPath(path);
        photo.setYear(calendar.get(Calendar.YEAR));
        photo.setWeek(calendar.get(Calendar.DAY_OF_WEEK));
        boolean save = photo.save();
        if (save) {
            boolean result = list.add(photo);
            LogUtils.d(TAG, "----图片保存数据库-- " + result);
            File dir = new File(PathUtil.getAppPicPath());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            LogUtils.d(TAG, "图片保存本地路径： " + path);
            ThreadTask.getInstance().executorOtherThread(new SaveImageRunnable(date, path), ThreadTask.ThreadPeriod.PERIOD_HIGHT);
        }

    }


    @Override
    protected void onPause() {
        super.onPause();
        mBinding.glCamera.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mBinding.glCamera.onResume();
    }

    private void getCameraPreSize() {
        if (CameraUtil.getInstance().getIsPreview()) {
            List<Camera.Size> previewSizeList = CameraUtil.getInstance().getPreviewSizeList();
            for (Camera.Size size :
                    previewSizeList) {
                LogUtils.d(TAG, " width = " + size.width + "  height = " + size.height);
            }
        }
    }

    private void getCameraSupportSaveSize() {
        if (CameraUtil.getInstance().getIsPreview()) {
            List<Camera.Size> previewSizeList = CameraUtil.getInstance().getPictureSizeList();
            for (Camera.Size size :
                    previewSizeList) {
                LogUtils.d(TAG, " width = " + size.width + "  height = " + size.height);
            }
        }
    }

    public void getZoomCamera() {
        if (CameraUtil.getInstance().getIsPreview()) {
            List<Integer> zoomCameraList = CameraUtil.getInstance().getZoomCameraList();
            for (Integer size :
                    zoomCameraList) {
                LogUtils.d(TAG, " size = " + size);
            }
        }
    }
}
